import {
  listUser,
  resetUserPwd,
  changeUserStatus,
  addOrEditAdmin, deleteAdmin, changeAdminLocked
} from '@/api/system/user'
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { getRoles, getRolesById } from '@/api/system/role'
import { validPassWord } from '@/utils/validate'

export default {
  name: "User",
  components: { Treeselect },
  data() {
    const validatePassword = (rule,value,callback) =>{
      if (!value){
        callback(new Error('密码不能为空'));
      }else {
        let b = validPassWord(value)
        if (!b){
          callback(new Error("密码最少6位，包括至少1个大写字母，1个小写字母，1个数字"))
        }
        callback()
      }
    };
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: null,
      // 是否显示弹出层
      open: false,
      openEdit:false,
      // 日期范围
      dateRange: [],
      // 状态数据字典
      lockedOptions: [
        {
          dictLabel:"启用",
          dictValue:false
        },
        {
          dictLabel:"锁定",
          dictValue:true
        }
      ],
      // 角色选项
      roleOptions: [],
      chooseRoles:[],
      chooseVisible:false,
      roles:[],
      roleTotal:0,
      roleQuery:{
        current: 1,
        size: 10
      },
      getIds:[],
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        adminName: undefined,
        phone: undefined,
        roleName: undefined,
        locked:undefined
      },
      // 表单校验
      rules: {
        adminName: [
          { required: true, message: "用户名称不能为空", trigger: "blur" }
        ],
        nickName: [
          { required: true, message: "用户昵称不能为空", trigger: "blur" }
        ],
        passWord: [
          { required: true,validator: validatePassword, trigger: "blur" }
        ],
        phone: [
          { required: true, message: "手机号码不能为空", trigger: "blur" },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询用户列表 */
    getList() {
      this.loading = true;
      listUser(this.queryParams).then(res=> {
          this.userList = res.page.records;
          this.total = res.page.total;
          this.loading = false;
        }
      );
    },
    //角色标签关闭
    handleClose(tag) {
      this.chooseRoles.splice(this.chooseRoles.indexOf(tag), 1);
    },
    //添加角色按钮
    addRoles(){
      this.getRoles();
      this.chooseVisible =true;
    },
    //获取角色列表
    getRoles(){
      getRoles(this.roleQuery)
        .then(res=>{
          this.roles = res.roles.records;
          this.roleTotal = res.roles.total;
          let roles = this.roles;
          let chooseRoles = this.chooseRoles;
          let arr = [];
          chooseRoles.forEach((item)=>{
            arr.push(item.id);
          })
          this.$nextTick(()=>{
            roles.forEach((item)=>{
              if (arr.indexOf(item.id)!=-1){
                this.$refs.multipleTable.toggleRowSelection(item,true);
              }
            })
          })
        })
    },
    rolePageChange(val){
      this.$set(this.roleQuery,'current',val);
      this.getRoles();
    },
    //选择角色的操作
    rolesSelectionChange(val){
      this.chooseRoles = val;
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    //删除角色关系
    deleteRole(admin,tag){
      this.$confirm('删除用户角色后某些功能将不被支持，请谨慎操作！', '提示', {
        type: 'warning',
      })
        .then(()=>{
          this.chooseRoles.splice(this.chooseRoles.indexOf(tag), 1);
          let arr=[];
          this.chooseRoles.forEach(it=>{
            arr.push(it.id);
          })
          this.form.roleIds=arr;
        })
        .catch(()=>{})

    },
    // 用户状态修改
    handleStatusChange(row) {
      let text = row.locked === true ? "锁定" : "开启";
      this.$confirm('确认要' + text + row.adminName + '用户吗?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        let admin = {}
        admin.id = row.adminId
        admin.locked = row.locked
        return changeAdminLocked(admin);
      }).then(() => {
        this.msgSuccess(text + "成功");
      }).catch(function() {
        row.status = row.status === true ? false : true;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    cancelEdit() {
      this.openEdit = false;
    },
    // 表单重置
    reset() {
      this.form = {
        userId: undefined,
        adminName: undefined,
        nickName: undefined,
        password: undefined,
        phone: undefined,
        email: undefined,
        sex: undefined,
        status: "0",
        remark: undefined,
        roleIds: []
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.form.locked = false
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.form = row;
      this.openEdit = true;
      this.form.passWord = null;
      let ids = this.form.roleIds
      if (ids && ids.length>0){
        this.getIds = ids;
        if (this.getIds.length<=0)return;
        getRolesById(this.getIds)
          .then(res=>{
            this.chooseRoles = res.roles;
            this.getIds = [];
          })
      }
    },
    /** 重置密码按钮操作 */
    handleResetPwd(row) {
      this.$prompt('请输入' + row.adminName + '的新密码', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消"
      }).then(({ value }) => {
        let admin = {}
        admin.id = row.adminId
        admin.passWord = value;
        resetUserPwd(admin).then(res => {
          this.msgSuccess("修改成功!" );
        });
      }).catch(() => {});
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          let roles = this.chooseRoles
          if (roles.length>0){
            roles.forEach(it=>{
              this.form.roleIds=[];
              this.form.roleIds.push(it.id);
            })
            this.chooseRoles=[];
          }
          if (this.form.adminId){
            this.form.passWord = null
          }
          addOrEditAdmin(this.form).then(res=>{
              if (res.success==true){
                if (this.form.adminId){
                  this.msgSuccess("修改成功");
                  this.openEdit = false;
                  this.getList();
                }else {
                  this.msgSuccess("新增成功");
                  this.open = false;
                  this.getList();
                }
              }
            })
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      let admin={}
      admin.id = row.adminId;
      this.$confirm('是否确认删除' + row.adminName + '的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return deleteAdmin(admin);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      })
    },
  }
};
